// pages/newIndex/newIndex.js
var util = require('../../utils/util') // 引入配置公共请求接口
var configUrl = require('../../config/config') // 引入配置接口文件
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    footprintGuid: '', // 足迹全局id
    topFixed: false,
    isShowPartnerAll:true,
    bgimgUrl: getApp().globalData.BgimgUrl,
    logoImg: getApp().globalData.BgimgUrl + 'logoImg.png', // logo
    indexLoadingPic: getApp().globalData.BgimgUrl + 'index_load_pic.png', // 首页占位图
    topBgimg: '', // 顶部背景图
    img: getApp().globalData.img,
    imgUrl: getApp().globalData.imgUrl,
    bodyBgPic: '',
    pinOnTop: '',
    placeholderText: '',
    componentList: [], // 组件集合
    title: '附近门店',
    showExitPreview: false,
    showIndexLoading: true,
    indexLoadingErrMsg: '首页加载中...',
    showIndexLoadingErrMsg: false,
    reOpenIndex: false
  },
  initData: function(options) {
    console.log('主页初始数据')
    const that = this
    if (!wx.getStorageSync('reOpenIndex')) {
      wx.setStorageSync('reOpenIndex', true)
    } else {
      that.setData({
        reOpenIndex: true
      })
    }
    // 获取设置，用于判断是否在小程序内(可能有更好的判断方法)
    wx.getSetting({
      success(res) {
        that.setNavHeight()
        // that.getTopTheme()
        // that.getSeckillTheme()
        console.log('主页调用app.js定位')
        that.getUserLocation((res2) => {
          // debugger
          var address = wx.getStorageSync('addrCode')
          that.getnearby(address)
          var showAddressData = address.province + address.city + address.district + address.townName
          that.setData({
            thisAddress: address.city
          })
          that.setData({
            showAddressData: showAddressData
          })
        })
        const addrCode = wx.getStorageSync('addrCode')
        that.setData({
          addrCode: addrCode
        })
        wx.removeStorageSync('selectAddId')
        wx.removeStorageSync('nowBuyDepositSku')
        if (options && (options.scene || options.hid)) {
          var scene = options.hid ? options.hid : decodeURIComponent(options.scene) // 参数二维码传递过来的参数
          if (options.hid) {
            var stInFun = setInterval(() => {
              if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
                clearInterval(stInFun)
                if (!wx.getStorageSync('loginMsg').loginState) {
                  if (wx.getUserProfile) {
                    app.getUserProfile(function() {
                      that.setData({
                        getPhoneNumberData: {
                          isShowGetPhoneNumber: true
                        }
                      })
                    })
                  } else {
                    if (!wx.getStorageSync('loginMsg').bindingPhone) {
                      that.setData({
                        getPhoneNumberData: {
                          isShowGetPhoneNumber: true
                        }
                      })
                    }
                  }
                  // that.setData({
                  //   isShowGetUserInfo: true
                  // })
                }
                if (wx.getStorageSync('previewTemplateId')) {
                  that.setData({
                    showExitPreview: true
                  })
                  that.getComponentData(wx.getStorageSync('previewTemplateId'))
                } else {
                  that.getComponentData()
                }
                // if (!wx.getStorageSync('firstTiped')) {
                //   wx.setStorageSync('firstTiped', true)
                //   wx.showModal({
                //     title: '温馨提示',
                //     content: '欢迎光临全友商城',
                //     showCancel: false,
                //     success (res) {
                //       if (res.confirm) {
                //         console.log('用户点击确定')
                //       }
                //     }
                //   })
                // }
                app.bindingPartner(options.hid)
                
              }
            }, 500)
          } else {
            app.getShareCode(scene, (res) => {
              var stInFun = setInterval(() => {
                if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
                  clearInterval(stInFun)
                  if (!wx.getStorageSync('loginMsg').loginState) {
                    if (wx.getUserProfile) {
                      app.getUserProfile(function() {
                        that.setData({
                          getPhoneNumberData: {
                            isShowGetPhoneNumber: true
                          }
                        })
                      })
                    } else {
                      if (!wx.getStorageSync('loginMsg').bindingPhone) {
                        that.setData({
                          getPhoneNumberData: {
                            isShowGetPhoneNumber: true
                          }
                        })
                      }
                    }
                    // that.setData({
                    //   isShowGetUserInfo: true
                    // })
                  }
                  that.getComponentData(res.templateId)
                  // if (!wx.getStorageSync('firstTiped')) {
                  //   wx.setStorageSync('firstTiped', true)
                  //   wx.showModal({
                  //     title: '温馨提示',
                  //     content: '欢迎光临全友商城',
                  //     showCancel: false,
                  //     success (res) {
                  //       if (res.confirm) {
                  //         console.log('用户点击确定')
                  //       }
                  //     }
                  //   })
                  // }
                  if (res.userId) {
                    app.bindingPartner(res.userId)
                  }
                  // 这里存下预览的模板id
                  that.setData({
                    showExitPreview: true
                  })
                  wx.setStorageSync('previewTemplateId', res.templateId)
                }
              }, 500)
            })
          }
        } else {
          var stInFun = setInterval(() => {
            if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
              clearInterval(stInFun)
              if (wx.getStorageSync('previewTemplateId')) {
                that.setData({
                  showExitPreview: true
                })
                that.getComponentData(wx.getStorageSync('previewTemplateId'))
              } else {
                that.getComponentData()
              }
              // if (!wx.getStorageSync('firstTiped')) {
              //   wx.setStorageSync('firstTiped', true)
              //   wx.showModal({
              //     title: '温馨提示',
              //     content: '欢迎光临全友商城',
              //     showCancel: false,
              //     success (res) {
              //       if (res.confirm) {
              //         console.log('用户点击确定')
              //       }
              //     }
              //   })
              // }
            }
          }, 500)
        }
      },
      fail(res) {
        // 拿不到设置，视为微信朋友圈单页
        that.getComponentData()
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.initData(options)
  },
  setNavHeight: function() {
    const sysInfo = wx.getSystemInfoSync()
    const statusHeight = sysInfo.statusBarHeight
    this.setData({
      statusHeight
    })
  },
  // 监听页面滚动距离scrollTop
  onPageScroll: function(e) {
    var that = this
    // 3.当页面滚动距离scrollTop > 菜单栏距离文档顶部的距离时，菜单栏固定定位
    if (e.scrollTop > 30) {
      that.setData({
        topFixed: true
      })
    } else {
      that.setData({
        topFixed: false
      })
    }
  },
  // 获取头部背景图
  getComponentData(templateId) {
    const that = this
    const formdata = {}
    formdata.page = 1
    formdata.rows = 10
    formdata.pageFlag = false
    if (templateId) {
      const rawJson = [{ 'id': 'templateId', 'property': 'templateId', 'value': templateId, 'operator': '=' }]
      formdata.filtersRaw = JSON.stringify(rawJson)
    }

    app.reqFun.requestForm('POST', configUrl.componentData, formdata, (res) => {
      if (res.data.success == 1) {
        if (res.data.data.total == 0) {
        // 无组件直接结束
          return
        }
        that.setData({
          showIndexLoading: false
        })
        if (res.data.data) {
          if (res.data.data.pcsBgComponent) {
            const bgDetail = res.data.data.pcsBgComponent.componentDetail
            this.setData({
              bgDetail: bgDetail,
              pinOnTop: bgDetail && bgDetail.pinOnTop
            })
            if (bgDetail && bgDetail.bodyBgPic) {
              this.setData({
                bodyBgPic: this.data.imgUrl + bgDetail.bodyBgPic
              })
            }
            if (bgDetail && bgDetail.topPinBgPic) {
              this.setData({
                topBgimg: this.data.imgUrl + bgDetail.topPinBgPic
              })
            }
          }
          const componentList = res.data.data.componentList
          this.setData({
            componentList: componentList
          })
          for (var i = 0; i < componentList.length; i++) {
            if (componentList[i].componentType == 'search') {
              this.setData({
                pinOnTop: componentList[i].componentDetail.pinOnTop,
                placeholderText: componentList[i].componentDetail.placeholderText
              })
            }
          }
        }
      } else {
        that.setData({
          indexLoadingErrMsg: res.data.msg,
          showIndexLoadingErrMsg: true
        })
        setTimeout(() => {
          wx.showToast({
            title: res.data.msg,
            icon: 'error'
          })
          setTimeout(() => {
            wx.hidenToast()
          }, 5000)
        }, 0)
      }
    })
  },

  // 获取头部背景图
  //  getTopTheme() {
  //   app.reqFun.requestJson('POST',configUrl.sysTheme + `/${'homeTop'}`,'',(res)=>{
  //     if(res.data.success==1){
  //       if (res.data.data) {
  //         let headBgimg = this.data.imgUrl + res.data.data.bgPic
  //         let topBgimg = this.data.imgUrl + 'group1/M01/01/A2/rB8MkmFNiRKAaFjQAAHWf7jdP0I228.JPG'
  //         this.setData({
  //           headBgimg: headBgimg,
  //           topBgimg: topBgimg
  //         })
  //       } else {
  //         this.setData({
  //           headBgimg: this.data.bgimgUrl + 'headBgimg.png'
  //         })
  //       }
  //     }
  //   })
  // },
  // 展开合伙人信息
  showPartnerAll: function() {
    this.setData({
      isShowPartnerAll:!this.data.isShowPartnerAll
    })
  },
  // 展示合伙人二维码
  partnerCode: function(e) {
    const codeImg = e.target.dataset.url
    wx.previewImage({
      urls: [codeImg],
      current: codeImg // 当前显示图片的http链接
    })
  },
  // 关闭合伙人二维码
  closeCodePop: function() {
    this.setData({
      showPartnerCodePop: false
    })
  },
  // 拨打合伙人电话
  partnerPhone: function() {
    const that = this
    wx.makePhoneCall({
      phoneNumber: that.data.partnerInfo.partnerPhone
    })
  },
  // 获取用户地理位置
  getUserLocation: function(callback) {
    // if (wx.getStorageSync('indexGetLocationIng')) {
    //   return
    // }
    // wx.setStorageSync('indexGetLocationIng', true)
    const that = this
    app.getUserLocation(() => {
      // const res = wx.getStorageSync('locationInfo')
      // const latitude = res.latitude
      // const longitude = res.longitude
      // var laorln = util.qqMapTransBMap(latitude, longitude)
      // wx.setStorageSync('latAndLong', laorln)
      let addrCode = wx.getStorageSync('addrCode')
      const address = addrCode.province + addrCode.city + addrCode.district + addrCode.street + addrCode.townName + addrCode.streetNumber
      that.getnearby(address)
      that.setData({
        thisAddress: addrCode.city
      })
      // wx.setStorageSync('indexGetLocationIng', false)
      callback()
    })
  },
  goSearchPage(e) { // 商品搜索进入商品列表
  // this.getLogin((re)=>{
  //   if(re){
    const placeholderText = this.data.placeholderText
    const type = 's'
    wx.navigateTo({
      url: '/packageShop/pages/shopSearch/shopSearch?type=' + type + '&placeholderText=' + placeholderText
    })
  //   }
  // })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    // console.log('页面加载完成99999999999999', wx.createSelectorQuery().selectAll('.cardLow'))
    // wx.createSelectorQuery().selectAll('#cardLow').boundingClientRect(function(rect) {
    //   console.log('rect1233333333333333333', rect)
    // }).exec()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow(options) {
    this.setData({
      footprintGuid: util.guid()
    })
    setTimeout(()=>{
      this.setData({
        partnerInfo:getApp().globalData.partnerInfo
      })
      },500)
    // 保存访问足迹
    app.saveAccessFootprint(this.data.footprintGuid, 'newIndex', null)
    const  shareUserId=getApp().globalData.shareUserId
    if (shareUserId) {
    let dataList =await this.getShareShops(shareUserId)
    if(dataList.length>0) {
            this.setData({
            nowShowNearby: dataList[0],
            title: '推荐门店'
          })
     }else{
      this.onLoad()
     }
    }else{
      this.onLoad()
    }
  },
  // 根据用户ID获取所属门店
  getShareShops(user){
    return new Promise((resolve,reject)=>{
      app.reqFun.requestJson('get',configUrl.recommendShop+'/'+user,{},(res)=>{
        if(res.data.success==1&&res.data.data.length>0){
          resolve (res.data.data)
        }else{
          resolve ([])
        }
      })
  })
   },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    // 保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // 保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },
  getnearby(data) { // 获取附近门店---地址换取经纬度
    var that = this
    var parms = {
      address: data
    }
    app.reqFun.requestJson('get', configUrl.geocode, parms, (res) => {
      if (res.data.success == 1) {
        that.nearbyShop(res.data.data.latitude, res.data.data.longitude)
      }
    })
  },
 async nearbyShop(lat, long) { // 经纬度获取附近门店   distance范围 latitude纬度   longitude 经度
    const shareUserId = app.globalData.shareUserId
    var that = this
    var parms = {
      distance: 100000,
      latitude: lat,
      longitude: long
    }
    if (shareUserId) {
      let shareShops =await  this.getShareShops(shareUserId)
      if(shareShops.length>0) {
        this.setData({
          nowShowNearby:shareShops[0],
          title: '推荐门店'
        })
      } else {
        // 合伙人没有推荐门店则按距离展示门店
        this.getnearbyShop(parms)
          // let shopList = await this.getShareShops(wx.getStorageSync('loginMsg').userId)
          // if(shopList.length>0){
          //   this.setData({
          //     nowShowNearby: shopList[0],
          //     title: '推荐门店'
          //   })
          // }else{
          //   // 合伙人没有推荐门店则按距离展示门店
          // this.getnearbyShop(parms)
          // }
        }
    } else {
      this.getnearbyShop(parms)
      // let shopList =await  this.getShareShops(wx.getStorageSync('loginMsg').userId)
      // if(shopList.length>0){
      //   this.setData({
      //     nowShowNearby: shopList[0],
      //     title: '推荐门店'
      //   })
      // }else{
      //   // 合伙人没有推荐门店则按距离展示门店
      // this.getnearbyShop(parms)
      // }
    }
  },
  getnearbyShop(parms) {
    var that = this
    app.reqFun.requestJson('get', configUrl.nearbyShop, parms, (res) => {
      if (res.data.success && res.data.data.length > 0) {
        console.log('附近门店', res.data.data[0])
        let storesData = res.data.data[0]
        wx.getSetting({
          success(res) {
            //这里判断是否有定位权限
            if (!res.authSetting['scope.userLocation']) {
              storesData.name = '暂无附近门店'
              storesData.address = '您未开启定位，无法匹配附近门店'
              that.setData({
                nowShowNearby: storesData,
                title: '附近门店'
              })
            } else {
              that.setData({
                nowShowNearby: storesData,
                title: '附近门店'
              })
            }
          }
        })
      } else {
        that.setData({
          nowShowNearby: '',
          title: '附近门店'
        })
      }
    }, true)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    return {
      title: '全友家居官方商城',
      desc: '全友家居官方商城',
      path: '/pages/newIndex/newIndex?hid=' + wx.getStorageSync('loginMsg').userId
    }
  },

  /**
   * 用户点击右上角分享朋友圈
   */
  onShareTimeline: function() {
    const queryParam = 'hid=' + wx.getStorageSync('loginMsg').userId
    return {
      title: '全友家居官方商城',
      query: queryParam,
      imageUrl: ''
    }
  },
  /**
   * 退出首页预览
   */
  exitPreview() {
    wx.removeStorageSync('previewTemplateId')
    wx.reLaunch({
      url: '/pages/newIndex/newIndex'
    })
    this.setData({
      showExitPreview: false
    })
  },

  /**
   * 设置弹窗-继续浏览
   */
  continueView: function () {
      wx.setStorageSync('showSetting', false)
      this.setData({showSetting: false})
      this.initData()
  },

  /**
   * 获取真实定位
   */
  getRealLocation: function () {
    let that = this
    app.getRealLocation(resp => {
      if (resp && resp.showSetting == false) {
        that.initData()
      }
      if (resp && resp.showSetting == true) {
        that.setData({showSetting: true})
      }
    })
  },
  
  onMyEvent: function(e) {
    let that = this
    if (e.detail.showSetting) {
      that.setData({showSetting: true})
    }
  },
  goCrm(){
    wx.navigateTo({
      url: '/packagBuy/pages/found/crmweb/index',
    })
  }
})
